package com.lemon.smartsafety.ui.fragment.setting;

import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.lemon.android.http.HttpUtils;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.ApplicationInfo;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.data.app.DataUtil;
import com.lemon.smartsafety.entity.bind.BindVo;
import com.lemon.smartsafety.entity.common.UploadFileItem;
import com.lemon.smartsafety.entity.event.base.AppEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.event.main.drawer.DrawerRefreshEvent;
import com.lemon.smartsafety.entity.event.user.LoginOutEvent;
import com.lemon.smartsafety.entity.event.user.MyHeaderImgEvent;
import com.lemon.smartsafety.entity.event.user.MyNoticeEvent;
import com.lemon.smartsafety.entity.event.user.MyScoreEvent;
import com.lemon.smartsafety.entity.event.user.UserSetRefreshEvent;
import com.lemon.smartsafety.entity.user.ProfileBaseModel;
import com.lemon.smartsafety.entity.user.ProfileCommonModel;
import com.lemon.smartsafety.entity.user.ProfileHeadModel;
import com.lemon.smartsafety.entity.user.UploadIcon;
import com.lemon.smartsafety.entity.version.VersionVo;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.MainFragmentServices;
import com.lemon.smartsafety.http.service.UpdateServices;
import com.lemon.smartsafety.listener.GlidePauseOnScrollListener;
import com.lemon.smartsafety.result.OldBaseMode;
import com.lemon.smartsafety.result.user.UserIconMode;
import com.lemon.smartsafety.ui.activity.user.BindEmailActivity;
import com.lemon.smartsafety.ui.activity.user.LoginActivity;
import com.lemon.smartsafety.ui.activity.user.ModifyPasswordActivity;
import com.lemon.smartsafety.ui.activity.user.MyScoreActivity;
import com.lemon.smartsafety.ui.activity.user.SettingUrlActivity;
import com.lemon.smartsafety.ui.adapter.profile.ProfileAdapter;
import com.lemon.smartsafety.ui.adapter.profile.ProfileHeadItemView;
import com.lemon.smartsafety.ui.adapter.profile.ProfileTag;
import com.lemon.smartsafety.ui.adapter.profile.ProfileViewType;
import com.lemon.smartsafety.ui.fragment.MainFragment;
import com.lemon.smartsafetynew.ui.fragment.base.ToolbarBaseFragment;
import com.lemon.smartsafety.update.UpdateManager;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.ImgLoadUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.app.SharedPreferencesServer;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.AppUtils;
import com.lemon.smartsafety.utils.common.FileUtil;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.utils.photo.GlideImageLoader;
import com.lemon.smartsafety.view.dialog.DialogChoice;

import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.PauseOnScrollListener;
import cn.finalteam.galleryfinal.ThemeConfig;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Created by Cooliean on 16/1/25.
 */
public class UserProfileFragment extends ToolbarBaseFragment {
    private RecyclerView mRecyclerView;

    private MaterialDialog.Builder mMaterialDialog;

    private List<ProfileBaseModel> items = new ArrayList<ProfileBaseModel>();
    private List<ProfileCommonModel> commonModelList = new ArrayList<>();

    private ProfileAdapter mAdapter;


    //以下是裁剪
    private SharedPreferencesServer mSharedPreferencesServer;

    private ThemeConfig mThemeConfig = null;
    private FunctionConfig.Builder mFunctionConfigBuilder = null;
    private CoreConfig.Builder mCoreConfigBuilder = null;
    /**
     * 最大的选择照片数量
     */
    private int mMaxSize = 1;
    /**
     * 是否不使用动画
     */
    private boolean bNoAnimation = true;
    private DialogChoice dialogChoice = null;
    private final int REQUEST_CODE_CAMERA = 1000;
    private final int REQUEST_CODE_GALLERY = 1001;
    private final int REQUEST_CODE_CROP = 1002;
    private UploadFileItem uploadFileItem;
    private List<UploadFileItem> uploadFileItemList;
    private Gson mGson;

    //用户头像
    private UserIconMode userIconMode;



    public static UserProfileFragment newInstance() {
        UserProfileFragment mainFragment = new UserProfileFragment();
        return mainFragment;
    }

    @Override
    protected int getTitle() {
        return R.string.user_profile_main_title;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_profile;
    }

    @Override
    protected void initViews() {
        super.initViews();
        initData();
        //裁剪相关
        initGalleryFinal();

        mGson = new Gson();
        mRecyclerView = getViewById(R.id.recyclerView);

        mAdapter = new ProfileAdapter(items);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initData() {
        items.clear();
        if (mSharedPreferencesHelper.isLogin()) {
            ProfileHeadModel profileHeadModel = new ProfileHeadModel();
            profileHeadModel.setUserName(mSharedPreferencesHelper.getUserName());
            profileHeadModel.setUserType(StringUtils.nullValue(mSharedPreferencesHelper.getUserTypeName()));
            profileHeadModel.setViewType(ProfileViewType.TYPE_HEAD);
            profileHeadModel.setIconPath(StringUtils.nullValue(HttpUtils.formatFilesUrl(mSharedPreferencesHelper.getUserPhotoUrl())));
            items.add(profileHeadModel);

            ProfileBaseModel baseModel = new ProfileBaseModel();
            baseModel.setViewType(ProfileViewType.TYPE_SECTION_HEAD);
            items.add(baseModel);
        }


        commonModelList.clear();
        /*//根据登录状态获取数据 */
        commonModelList.addAll(DataUtil.getProfileItems(mSharedPreferencesHelper.isLogin()));//根据登录状态获取数据

        items.addAll(commonModelList);


        if (mSharedPreferencesHelper.isLogin()) {
            DataUtil.getProfileCommonItemByTag(commonModelList, ProfileTag.TAG_AREA)
                    .setValue(mSharedPreferencesHelper.getUserPlaceInfo());
            DataUtil.getProfileCommonItemByTag(commonModelList, ProfileTag.TAG_EMAIL)
                    .setValue(mSharedPreferencesHelper.getEmail());
            this.setTitle(getString(R.string.profile_title));
        } else {
            this.setTitle(getString(R.string.profile_title_no_login));
        }


        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }

    }

    @Subscribe
    public void onEventMainThread(AppEvent event) {
        if (EventTag.TAG_PROFILE_EXIST.equals(event.getTag())) {
            mMaterialDialog = new MaterialDialog.Builder(getActivity()).title(R.string.tip_str_title).content(R.string.profile_exist_sure).positiveText(R.string.sure_str).negativeText(R.string.cancel_str).onAny(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    if (which == DialogAction.POSITIVE) {
                        doExist();
                    }
                }
            });
            mMaterialDialog.show();
        } else if (ProfileTag.TAG_PASSWORD.toString().equals(event.getTag())) {//修改密码
            UIHelper.showActivity(getActivity(), ModifyPasswordActivity.class);
        } else if (LoginActivity.class.getName().equals(event.getTag())) {//登录成功后执行
            initData();
        } else if (SettingUrlActivity.class.getName().equals(event.getTag())) {//SettingUrlActivity 后回传刷新界面  修改了服务器地址，要注销
            doExist();
        } else if (ProfileTag.TAG_SETTING.toString().equals(event.getTag())) {//服务器设置
            UIHelper.showUrlSettingActivity(getActivity());
        } else if (ProfileTag.TAG_EMAIL.toString().equals(event.getTag())) {//绑定邮箱
            if (mSharedPreferencesHelper.isLogin()) {
                UIHelper.showActivity(getActivity(), BindEmailActivity.class);
            }
            //mHUDUtil.showDeveloper();
        } else if (ProfileTag.TAG_UPDATE.toString().equals(event.getTag())) {//更新事件
            UpdateServices.init().getUpdateInfo(AppUtils.getVersionCode(IApplication.context()));
        } else if (ProfileTag.TAG_FIRE_SETTING.toString().equals(event.getTag())) {//消防服务器设置
            UIHelper.showFireUrlSettingActivity(getActivity());
        }
    }


    /**
     * 我的公告
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(MyNoticeEvent event) {
        if (event.getTag().equals(ProfileHeadItemView.class.getName())) {
            MainFragmentServices.init().getBindInfo(ApplicationInfo.ApplicationCode.ANJIAN_NOTICE.getCode());
        }
    }

    /**
     * 我的积分
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(MyScoreEvent event) {
        if (event.getTag().equals(ProfileHeadItemView.class.getName())) {
            UIHelper.showActivity(getActivity(), MyScoreActivity.class);
        }
    }


    /**
     * 我的头像
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(MyHeaderImgEvent event) {
        if (event.getTag().equals(ProfileHeadItemView.class.getName())) {
            LogUtils.LOGE("点击了头像");
            if (mSharedPreferencesHelper.isLogin()) {
                showActionSheet();
            }

        }
    }


    /**
     * 初始化相机工具
     */
    private void initGalleryFinal() {
        mSharedPreferencesServer = new SharedPreferencesServer(IApplication.context());

        mThemeConfig = new ThemeConfig.Builder().setTitleBarBgColor(getResources().getColor(R.color.colorPrimary))
                .setTitleBarTextColor(getResources().getColor(R.color.colorWhite))
                .setTitleBarIconColor(getResources().getColor(R.color.colorWhite))
                .setFabNornalColor(getResources().getColor(R.color.colorPrimary))
                .setCheckSelectedColor(getResources().getColor(R.color.colorPrimary))//选择框选中颜色
                .setFabPressedColor(getResources().getColor(R.color.colorPrimaryDark))
                .build();
        mFunctionConfigBuilder = new FunctionConfig.Builder();
        cn.finalteam.galleryfinal.ImageLoader imageLoader = new GlideImageLoader();
        PauseOnScrollListener pauseOnScrollListener = new GlidePauseOnScrollListener(false, true);
        mFunctionConfigBuilder.setMutiSelectMaxSize(mMaxSize);


        mFunctionConfigBuilder.setEnableEdit(false);
        mFunctionConfigBuilder.setEnableRotate(true);
        mFunctionConfigBuilder.setRotateReplaceSource(false);

        mFunctionConfigBuilder.setEnableCrop(false);
        mFunctionConfigBuilder.setCropReplaceSource(false);
        mFunctionConfigBuilder.setCropSquare(false);
        mFunctionConfigBuilder.setForceCrop(false);//启动强制裁剪功能,一进入编辑页面就开启图片裁剪，不需要用户手动点击裁剪，此功能只针对单选操作
        mFunctionConfigBuilder.setForceCropEdit(false);//在开启强制裁剪功能时是否可以对图片进行编辑（也就是是否显示旋转图标和拍照图标）
        mFunctionConfigBuilder.setEnableCamera(true);
        mFunctionConfigBuilder.setEnablePreview(false);

        mCoreConfigBuilder = new CoreConfig.Builder(IApplication.context(), imageLoader, mThemeConfig).setFunctionConfig(mFunctionConfigBuilder
                .build())
                .setPauseOnScrollListener(pauseOnScrollListener)
                .setNoAnimcation(bNoAnimation);

        mCoreConfigBuilder.setTakePhotoFolder(new File(Environment.getExternalStorageDirectory(), "/DCIM/" + Constants.APP_TEMP_DIR + "/"));

        mCoreConfigBuilder.setEditPhotoCacheFolder(new File(FileUtil.getAppImagesDir(IApplication.context())));

        GalleryFinal.init(mCoreConfigBuilder.build());
    }


    //ImageUtils.getImageBase64Code(oldPath)    转base 64

    public void showActionSheet() {

        try {
            GalleryFinal.init(mCoreConfigBuilder.build());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (dialogChoice == null) {
            dialogChoice = new DialogChoice(getActivity());
        }

        dialogChoice.init(getActivity(), "取消", new DialogChoice.ClickBackInterface() {
            @Override
            public void callBackFunction(View view, int index) {
                if (index == 0) {//相机
                    mFunctionConfigBuilder.setEnableEdit(false);//这里如果打开了。返回结果后结束视图很慢不知道为什么
                    GalleryFinal.openCamera(REQUEST_CODE_CAMERA, mFunctionConfigBuilder.build(), mOnHanlderResultCallback);
                } else if (index == 1) {
                    mFunctionConfigBuilder.setEnableEdit(false);//这里如果打开了。返回结果后结束视图很慢不知道为什么
                    mFunctionConfigBuilder.setEnableCamera(true);
                    GalleryFinal.openGallerySingle(REQUEST_CODE_GALLERY, mFunctionConfigBuilder.build(), mOnHanlderResultCallback);
                }
            }
        }, "相机", "相册");
    }


    /**
     * 相机或者 相册返回
     */
    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {

            if (!CommonUtil.listIsEmpty(resultList)) {

                LogUtils.LOGE("选择的图片路径：" + resultList.get(0).getPhotoPath());
                GalleryFinal.openCropNew(REQUEST_CODE_CROP, mFunctionConfigBuilder.build(), resultList.get(0).getPhotoPath(), cropCallback);
            }

        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            mHUDUtil.setDefault();
            mHUDUtil.showErrorTip(errorMsg);
        }
    };


    /**
     * 裁剪返回
     */
    private GalleryFinal.OnHanlderResultCallback cropCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, final List<PhotoInfo> resultList) {

            if (!CommonUtil.listIsEmpty(resultList)) {

                LogUtils.LOGE("裁剪后的路径:" + resultList.get(0).getPhotoPath());
                try {
               /*     ProfileHeadModel profileHeadModel = (ProfileHeadModel) items.get(0);
                    profileHeadModel.setIconPath(resultList.get(0).getPhotoPath());
                    items.set(0, profileHeadModel);
                    mAdapter.notifyDataSetChanged();*/

                    AppService.getBus().post(new UploadIcon(resultList.get(0).getPhotoPath()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            mHUDUtil.setDefault();
            mHUDUtil.showErrorTip(errorMsg);
        }
    };

    /**
     * 上传头像
     */
    @Subscribe
    public void onEventMainThread(final UploadIcon uploadIcon) {

        if (!CommonUtil.strIsEmpty(uploadIcon.getPath())) {
            LogUtils.LOGE("裁剪完待上传图片:" + uploadIcon.getPath());
            getSingleUploadImgBase64(uploadIcon.getPath(), new transBase64CallBack() {
                @Override
                public void onStart() {
                    mHUDUtil.showHUD();
                }

                @Override
                public void onFinish(String data) {
                    if (CommonUtil.strIsEmpty(data)) {
                        mHUDUtil.hidden();
                    } else {
                        httpUploadIcon(data);
                    }
                }
            });
        }

    }


    private void httpUploadIcon(String data) {

        LemonRequestParams params = new LemonRequestParams("user_property_data ", "user_id", "");
        uploadFileItem = new UploadFileItem();
        uploadFileItemList = new ArrayList<>();
        uploadFileItemList.clear();
        uploadFileItem.setBase64(data);
        uploadFileItem.setExt(UploadFileItem.EXT_JPG);
        uploadFileItem.setOp(UploadFileItem.ADD);
        uploadFileItem.setType(UploadFileItem.TYPE_JPG);
        uploadFileItemList.add(uploadFileItem);

        params.put("files", mGson.toJson(uploadFileItemList));
        params.put("handler", "com.ifree.user_verify.UserImgAction");
        params.put("op", "new_save_user_img");
        params.put("_no_html", "1");

        SharedPreferencesServer mSharedPreferencesServer = new SharedPreferencesServer(getActivity());
        String serverUrl = mSharedPreferencesServer.getRequestUrl(HttpPath.ActionServlet_Icon);
        //Log.i("serverUrl=",serverUrl);
       // Log.i("params=",params.toString());

        HttpOkBase.httpBasePost(params, serverUrl, "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                if (httpClient) {
                    OldBaseMode baseMode = JsonUtils.fromJson(result, OldBaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (!baseMode.isIsError()) {
                           /* //通知主页刷新个人信息
                            AppService.getBus().post(new UpDateUserInfoEvent());*/
                            try {
                                userIconMode= JsonUtils.fromJson(mGson.toJson(baseMode.getResult()), UserIconMode.class);
                                mSharedPreferencesHelper.setUserPhotoUrl(StringUtils.nullValue(userIconMode.getName()));
                                initData();
                                //通知侧边栏刷新个人信息
                                AppService.getBus().post(new DrawerRefreshEvent());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } else {
                    Log.i("show ","网络连接失败");
                    //ToastUtil.show("网络连接失败");
                }
            }
        });

    }


    public static interface transBase64CallBack<T> {
        public void onStart();

        public void onFinish(String data);
    }


    private String tempString;

    private void getSingleUploadImgBase64(final String path, final transBase64CallBack mTransBase64CallBack) {

        if (mTransBase64CallBack == null) {
            return;
        }

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mTransBase64CallBack != null) {
                    mTransBase64CallBack.onStart();
                }
            }
        });
        if (CommonUtil.strIsEmpty(path)) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mTransBase64CallBack.onFinish("");
                }
            });
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                tempString = "";
                try {
                    tempString = ImgLoadUtil.bitmapToBase64(ImgLoadUtil.getBitmap(path,70));

                    //tempString = ImageUtils.getImageBase64Code(path);
                    tempString = StringUtils.nullValue(tempString);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (mTransBase64CallBack != null) {
                                mTransBase64CallBack.onFinish(tempString);
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


    /**
     * 刷新 个人信息
     */
    @Subscribe
    public void onEventMainThread(final UserSetRefreshEvent userSetRefreshEvent) {

        try {
            initData();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * http处理请求的处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {
        if (EventTag.TAG_UPDATE_INFO.equals(event.getTag())) {//版本更新部分逻辑
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    VersionVo item = (VersionVo) event.getObj();
                    if (null != item) {
                        boolean isForce = item.isForce();
                        UpdateManager updateManager = new UpdateManager(item.getVersionRemark(), item.getDownloadUrl(), item.getVersionName(), Constants.APP_DOWNLOAD_FILE_NAME, isForce, getActivity());
                        updateManager.checkUpdateInfo();
                    }
                } else {
                    mHUDUtil.showInfoTip(event.getMsg());
                }
            }
        } else if (EventTag.TAG_BIND_INFO_HTTP.equals(event.getTag())) {//获取绑定信息
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    BindVo bindVo = (BindVo) event.getObj();
                    MainFragment.handleBindInfo(mHUDUtil, getActivity(), bindVo, event.getOther().toString());
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }

    private void doExist() {
        mSharedPreferencesHelper.loginOut();
        initData();
        AppService.getBus().post(new LoginOutEvent());
        //通知侧边栏刷新个人信息
        AppService.getBus().post(new DrawerRefreshEvent());
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        try {
            GalleryFinal.setmCropCallback(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
